class Media < ActiveRecord::Base
  belongs_to :user
  belongs_to :category
  belongs_to :mediable, :polymorphic => true
  has_many :comments, :dependent => :destroy
  has_many :media_rating_logs, :dependent => :destroy
  validates_presence_of :user_id, :title
  has_permalink :title
  
  acts_as_fulltext_indexed [:title, :description]
  acts_as_taggable
  acts_as_viewable
  
  def permalink_for(str)
    PermalinkFu.escape(str)
  end

  def self.full_text_search(q, options = {})
    return nil if q.nil? or q==""
    default_options = {:limit => 15, :page => 1}
    options = default_options.merge options
    options[:offset] = options[:limit] * (options.delete(:page).to_i-1)
    results = Media.search(q, options)
    all_results = Media.search(q)
    return [all_results.size, results]
  end
  
  def remove_indexes
    index = FulltextIndex.find_by_indexable_type_and_indexable_id(self.class.to_s, self.id)
    index.destroy if index
  end
end
